﻿using System;
using System.Text;
using System.Threading;
using Core.Common.Monitor;
using Core.Function;
using Newtonsoft.Json.Linq;
using Tool.Web.HttpHelper;
using static Core.Common.Global;

namespace Core.Monitors
{
	public class BiliBangumi : Tool.Common.Monitor
	{
		int num = 0;
		bool isFirst = true;

		public BiliBangumi(object flag) : base(flag)
		{
			ClearAllCloseEvent();
			ClearAllStartEvent();
			CloseEvent += () => CQ.Log($"关闭了对{flag}的番剧监控任务");
			StartEvent += () => CQ.Log($"开启了对{flag}的番剧监控任务");
		}

		protected override void Handle()
		{
			JObject jObject;
			try
			{
				jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.bilibili.com/pgc/view/web/media?media_id=" + flag)));
			}
			catch (Exception ex)
			{
				CQ.Log($"本次番剧监控({flag})无数据,错误信息为:{ex.Message}");
				return;
			}
			if (isFirst)
			{
				try
				{
					num = jObject["result"]["episode_index"]["id"].ToObject<int>();
					isFirst = false;
				}
				catch (Exception)
				{
				}
			}
			else
			{
				int num2;
				try
				{
					num2 = jObject["result"]["episode_index"]["id"].ToObject<int>();
				}
				catch (Exception)
				{
					return;
				}
				if (num != num2)
				{
					string arg = BiliBili.EpParse(num2);
					MonitorInfo monitorInfo = BangumiInfo.Find((e) => e.flag == (string)flag);
					lock (monitorInfo)
					{
						foreach (MonitorItem item in monitorInfo.item)
						{
							if (item.status == 1)
							{
								if (item.type == 0)
								{
									CQ.SendGroupMessage(item.num, string.Format("你订阅的番剧【{0}】有新动态了\r\n{1}", jObject["result"]["title"], arg));
								}
								if (item.type == 1)
								{
									CQ.SendPrivateMessage(item.num, string.Format("你订阅的番剧【{0}】有新动态了\r\n{1}", jObject["result"]["title"], arg));
								}
								Thread.Sleep(1000);
							}
						}
					}
					num = num2;
				}
			}
		}
	}
}
